package vn.com.vega.chacha.v2.fragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.Appinstant;
import vn.com.vega.chacha.v2.SearchScreen;
import vn.com.vega.music.clientserver.JsonAlbum;
import vn.com.vega.music.clientserver.JsonArtist;
import vn.com.vega.music.clientserver.JsonPlaylist;
import vn.com.vega.music.clientserver.JsonSong;
import vn.com.vega.music.clientserver.JsonVideo;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.objects.SearchItem;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.view.adapter.AlbumListAdapter;
import vn.com.vega.music.view.adapter.ArtistListAdapter;
import vn.com.vega.music.view.adapter.PlaylistListAdapter;
import vn.com.vega.music.view.adapter.SongListAdapter;
import vn.com.vega.music.view.adapter.VideoListAdapter;
import vn.com.vega.music.view.adapter.base.AutoLoadingAdapter;
import vn.com.vega.music.view.adapter.base.AutoLoadingListener;
import vn.com.vega.music.view.custom.LoadingView;
import vn.com.vega.music.view.custom.LoadingView.RetryListener;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class ShowSearchResultFragment extends Fragment implements
		AutoLoadingListener, View.OnClickListener {
	public static final int SEARCH_SONG_INDEX = 0;
	public static final int SEARCH_VIDEO_INDEX = 1;
	public static final int SEARCH_ALBUM_INDEX = 2;
	public static final int SEARCH_PLAYLIST_INDEX = 3;
	public static final int SEARCH_ARTIST_INDEX = 4;

	public static final int SEARCH_ONLNE = 100;
	public static final int SEARCH_OFF_LINE = 101;

	private int typeSearch = SEARCH_ONLNE;
	private int categorySearch = SEARCH_SONG_INDEX;

	private String mSearchKey;
	private List<Object> mListSongResult = new ArrayList<Object>();
	private List<Object> mListVideoResult = new ArrayList<Object>();
	private List<Object> mListAlbumResult = new ArrayList<Object>();
	private List<Object> mListPlaylistResult = new ArrayList<Object>();
	private List<Object> mListArtistResult = new ArrayList<Object>();

	private SearchScreen mSearchScreen;
	private LoadingView mLoadingView;
	private Search search;
	private ListView mListResult;
	private View mHeaderListSong;
	private SongListAdapter mListSongAdapter;
	private VideoListAdapter mListVideoAdapter;
	private AlbumListAdapter mListAlbumAdapter;
	private PlaylistListAdapter mListPlaylistListAdapter;
	private ArtistListAdapter mListAtistAdapter;
	private DataStore mDataStore;
	private Appinstant mApp;
	private View mSelectSongPlay, mPlayAllSong;

	public ShowSearchResultFragment(String searchKey, int category, int type) {
		super();
		mSearchKey = searchKey;
		categorySearch = category;
		typeSearch = type;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mSearchScreen = (SearchScreen) getActivity();
		mApp = (Appinstant) mSearchScreen.getApplication();
		mDataStore = DataStore.getInstance();
		// mListSongAdapter = new
		if (!Util.checkStringIsemptyOrNull(mSearchKey)) {
			doSearch(mSearchKey, categorySearch, typeSearch);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View root = inflater.inflate(R.layout.list_song_feature, null);
		mLoadingView = (LoadingView) root
				.findViewById(R.id.loadingView_loading_list_feature);
		mListResult = (ListView) root.findViewById(R.id.lv_list_song);
//		mListResult.setOnItemClickListener(onItemClickListener);
		mHeaderListSong = root.findViewById(R.id.layout_header_list_song);
		mSelectSongPlay = mHeaderListSong
				.findViewById(R.id.tv_select_song_play);
		mPlayAllSong = mHeaderListSong.findViewById(R.id.tv_play_all_song);
		mSelectSongPlay.setOnClickListener(this);
		mPlayAllSong.setOnClickListener(this);
		return root;
	}


	public void setSearchType(int searchType) {
		if (typeSearch != searchType) {
			changeType(searchType);
		}
	}

	public void setSearchCategory(int category) {
		if (category < SEARCH_SONG_INDEX) {
			if (categorySearch != SEARCH_SONG_INDEX) {
				changeCategory(SEARCH_SONG_INDEX);
			}
		} else if (category > SEARCH_ARTIST_INDEX) {
			if (categorySearch != SEARCH_ARTIST_INDEX) {
				changeCategory(SEARCH_ARTIST_INDEX);
			}
		} else {
			if (categorySearch != category) {
				changeCategory(category);
			}
		}
	}

	public void doSearch(String key, int category, int type) {
		if (Util.checkStringIsemptyOrNull(key)) {
			return;
		}
		mListResult.setAdapter(null);
		mLoadingView.setRetryListener(retryListener);
		if (search != null) {
			search.cancel(true);
		}
		switch (category) {
		case SEARCH_SONG_INDEX:
			if (mListSongResult.size() > 0) {
				showListSongResult();
				return;
			}
			break;
		case SEARCH_VIDEO_INDEX:
			if (mListVideoResult.size() > 0) {
				showListVideoResult();
				return;
			}
			break;
		case SEARCH_ALBUM_INDEX:
			if (mListAlbumResult.size() > 0) {
				showListAlbumResult();
				return;
			}
			break;
		case SEARCH_PLAYLIST_INDEX:
			if (mListPlaylistResult.size() > 0) {
				showListPlaylistResult();
				return;
			}
			break;
		case SEARCH_ARTIST_INDEX:
			if (mListArtistResult.size() > 0) {
				showListArtistResult();
				return;
			}
			break;

		default:
			break;
		}

		search = new Search(mSearchScreen, category, type, key, this);
		search.execute();
	}

	RetryListener retryListener = new RetryListener() {

		@Override
		public void onRetry() {
			// TODO Auto-generated method stub
			doSearch(mSearchKey, categorySearch, typeSearch);
		}
	};

	public void setSearchKey(String newSearchKey) {
		if (Util.checkStringIsemptyOrNull(newSearchKey)) {
			return;
		}

		changeSearchKey(newSearchKey);
	}

	private void changeSearchKey(String newSearchKey) {
		mSearchKey = newSearchKey;
		mListSongResult.clear();
		mListVideoResult.clear();
		mListAlbumResult.clear();
		mListPlaylistResult.clear();
		mListArtistResult.clear();

		doSearch(mSearchKey, categorySearch, typeSearch);
	}

	private void changeCategory(int newCategory) {
		categorySearch = newCategory;
		doSearch(mSearchKey, categorySearch, typeSearch);
	}

	private void changeType(int newType) {
		typeSearch = newType;
		mListAlbumResult.clear();
		mListSongResult.clear();
		mListVideoResult.clear();
		mListPlaylistResult.clear();
		mListArtistResult.clear();
		mListSongAdapter = null;
		mListVideoAdapter = null;
		mListAlbumAdapter = null;
		mListPlaylistListAdapter = null;
		mListAtistAdapter = null;
		
		doSearch(mSearchKey, categorySearch, typeSearch);
	}

	private void showListSongResult() {
		mHeaderListSong.setVisibility(View.VISIBLE);
		if (typeSearch == SEARCH_OFF_LINE) {
			mListSongAdapter = new SongListAdapter(mSearchScreen, mListSongResult,
					true, ShowSearchResultFragment.class.getName());
			mListResult.setAdapter(mListSongAdapter);
		} else {
			mListSongAdapter = new SongListAdapter(mSearchScreen, mListSongResult,
					false, ShowSearchResultFragment.class.getName());
			mListResult.setAdapter(new AutoLoadingAdapter(mListSongAdapter, this));
		}
		
	}

	private void showListVideoResult() {
		mHeaderListSong.setVisibility(View.GONE);
		mListVideoAdapter = new VideoListAdapter(mSearchScreen,
				mListVideoResult, false);
		if (typeSearch == SEARCH_OFF_LINE) {
			mListResult.setAdapter(mListVideoAdapter);
		} else {
			mListResult.setAdapter(new AutoLoadingAdapter(mListVideoAdapter, this));
		}
	}

	private void showListAlbumResult() {
		mHeaderListSong.setVisibility(View.GONE);
		mListAlbumAdapter = new AlbumListAdapter(mSearchScreen,
				mListAlbumResult);
		if (typeSearch == SEARCH_OFF_LINE) {
			mListResult.setAdapter(mListAlbumAdapter);
		} else {
			mListResult.setAdapter(new AutoLoadingAdapter(mListAlbumAdapter, this));
		}
	}

	private void showListPlaylistResult() {
		mHeaderListSong.setVisibility(View.GONE);
		mListPlaylistListAdapter = new PlaylistListAdapter(mSearchScreen,
				mListPlaylistResult);
		if (typeSearch == SEARCH_OFF_LINE) {
			mListResult.setAdapter(mListPlaylistListAdapter);
		} else {
			mListResult.setAdapter(new AutoLoadingAdapter(mListPlaylistListAdapter, this));
		}
				
	}

	private void showListArtistResult() {
		mHeaderListSong.setVisibility(View.GONE);
		mListAtistAdapter = new ArtistListAdapter(mSearchScreen,
				mListArtistResult);
		if (typeSearch == SEARCH_OFF_LINE) {
			mListResult.setAdapter(mListAtistAdapter);
		} else {
			mListResult.setAdapter(new AutoLoadingAdapter(mListAtistAdapter, this));
		}
	}

	@Override
	public Activity getContext() {
		// TODO Auto-generated method stub
		return mSearchScreen;
	}

	@Override
	public List<Object> getMoreData() {
		// TODO Auto-generated method stub
		List<Object> result = new ArrayList<Object>();

		if (typeSearch == SEARCH_OFF_LINE) {
			return result;
		} else {
			switch (categorySearch) {
			case SEARCH_SONG_INDEX:
				JsonSong jsonSong = JsonSong.search(mSearchKey,
						mListSongAdapter.getCount());
				if (jsonSong.isSuccess()) {
					mListSongResult.addAll(jsonSong.songs);
					result.addAll(jsonSong.songs);
				}
				break;
			case SEARCH_VIDEO_INDEX:
				JsonVideo jsonVideo = JsonVideo.search(mSearchKey,
						mListVideoAdapter.getCount());
				if (jsonVideo.isSuccess()) {
					result.addAll(jsonVideo.videos);
				}
				break;
			case SEARCH_ALBUM_INDEX:
				JsonAlbum jsonAlbum = JsonAlbum.search(mSearchKey,
						mListAlbumAdapter.getCount());
				if (jsonAlbum.isSuccess()) {
					result.addAll(jsonAlbum.albums);
				}
				break;
			case SEARCH_PLAYLIST_INDEX:
				JsonPlaylist jsonPlaylist = JsonPlaylist.search(mSearchKey,
						mListPlaylistListAdapter.getCount());
				if (jsonPlaylist.isSuccess()) {
					result.addAll(jsonPlaylist.playlists);
				}
				break;
			case SEARCH_ARTIST_INDEX:
				JsonArtist jsonArtist = JsonArtist.search(mSearchKey,
						mListAtistAdapter.getCount());
				if (jsonArtist.isSuccess()) {
					result.addAll(jsonArtist.artists);
				}
				break;
			}
			return result;
		}
	}

	static class Search extends AsyncTask<Void, Void, Void> {
		WeakReference<SearchScreen> searchScreenReference;
		WeakReference<ShowSearchResultFragment> showResultReference;
		List<Object> listResult = new ArrayList<Object>();
		int category;
		int type;
		String key;

		public Search(SearchScreen searchScreen, int category, int type,
				String searchKey,
				ShowSearchResultFragment showSearchResultFragment) {
			searchScreenReference = new WeakReference<SearchScreen>(
					searchScreen);
			this.category = category;
			this.type = type;
			key = searchKey;
			showResultReference = new WeakReference<ShowSearchResultFragment>(
					showSearchResultFragment);
		}

		private boolean checkIsLive() {
			SearchScreen searchScreen = searchScreenReference.get();
			if (searchScreen == null || searchScreen.isDestroy) {
				return false;
			}
			return true;
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (!checkIsLive()) {
				return null;
			}
			ShowSearchResultFragment showSearchResultFragment = showResultReference
					.get();
			showSearchResultFragment.mDataStore.addSearchItem(new SearchItem(
					key, System.currentTimeMillis() + ""));
			if (ShowSearchResultFragment.SEARCH_ONLNE == showSearchResultFragment.typeSearch) {
				// Seach online
				switch (category) {
				case SEARCH_SONG_INDEX:
					JsonSong jsonSong = JsonSong.search(key, 0);
					if (jsonSong.isSuccess()) {
						listResult.addAll(jsonSong.songs);
					}
					break;
				case SEARCH_VIDEO_INDEX:
					JsonVideo jsonVideo = JsonVideo.search(key, 0);
					if (jsonVideo.isSuccess()) {
						listResult.addAll(jsonVideo.videos);
					}
					break;
				case SEARCH_ALBUM_INDEX:
					JsonAlbum jsonAlbum = JsonAlbum.search(key, 0);
					if (jsonAlbum.isSuccess()) {
						listResult.addAll(jsonAlbum.albums);
					}
					break;
				case SEARCH_PLAYLIST_INDEX:
					JsonPlaylist jsonPlaylist = JsonPlaylist.search(key, 0);
					if (jsonPlaylist.isSuccess()) {
						listResult.addAll(jsonPlaylist.playlists);
					}
					break;
				case SEARCH_ARTIST_INDEX:
					JsonArtist jsonArtist = JsonArtist.search(key, 0);
					if (jsonArtist.isSuccess()) {
						listResult.addAll(jsonArtist.artists);
					}
					break;
				}

			} else {
				// Search offline
				switch (category) {
				case SEARCH_SONG_INDEX:
					listResult.addAll(showSearchResultFragment.mDataStore
							.loadLocalSongByKey(key));
					break;
				// case SEARCH_VIDEO_INDEX:
				// break;
				// case SEARCH_ALBUM_INDEX:
				// break;
				// case SEARCH_PLAYLIST_INDEX:
				// break;
				// case SEARCH_ARTIST_INDEX:
				// break;

				default:
					break;
				}
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if (isCancelled() || !checkIsLive()) {
				return;
			}
			ShowSearchResultFragment showSearchResultFragment = showResultReference
					.get();
			if (listResult.size() > 0) {
				showSearchResultFragment.mLoadingView.loadingFinish(true, null);
				switch (category) {
				case SEARCH_SONG_INDEX:
					showSearchResultFragment.mHeaderListSong
							.setVisibility(View.VISIBLE);
					showSearchResultFragment.mListSongResult.addAll(listResult);
					showSearchResultFragment.showListSongResult();
					break;
				case SEARCH_VIDEO_INDEX:
					showSearchResultFragment.mListVideoResult
							.addAll(listResult);
					showSearchResultFragment.showListVideoResult();
					break;
				case SEARCH_ALBUM_INDEX:
					showSearchResultFragment.mListAlbumResult
							.addAll(listResult);
					showSearchResultFragment.showListAlbumResult();
					break;
				case SEARCH_PLAYLIST_INDEX:
					showSearchResultFragment.mListPlaylistResult
							.addAll(listResult);
					showSearchResultFragment.showListPlaylistResult();
					break;
				case SEARCH_ARTIST_INDEX:
					showSearchResultFragment.mListArtistResult
							.addAll(listResult);
					showSearchResultFragment.showListArtistResult();
					break;

				default:
					break;
				}
			} else {
				showSearchResultFragment.mLoadingView.loadingFinish(false,
						"Không có kết quả!");
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			if (!checkIsLive()) {
				return;
			}
			ShowSearchResultFragment showSearchResultFragment = showResultReference
					.get();
			showSearchResultFragment.mLoadingView.startLoading();
			showSearchResultFragment.mLoadingView.setVisibility(View.VISIBLE);
		}

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (search != null) {
			search.cancel(true);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tv_select_song_play:
			if (mListSongAdapter != null && mListSongAdapter.getCount() > 0) {
				mListSongAdapter.selectSongPlay("Search result");
			}
			break;
		case R.id.tv_play_all_song:
			if (mListSongAdapter != null && mListSongAdapter.getCount() > 0) {
				mListSongAdapter.playAllSong("Search result");
			}
			break;

		default:
			break;
		}
	}

}
